import { MessageBox } from 'element-ui';
import dayjs from 'dayjs';
import { loadTaskLogsApi } from '@/api';
import { ListStore } from '@/store';
import { errorHandler } from '@/utils';
import { export_json_to_excel, formatJson } from '@/utils/vendor/Export2Excel';
import {
  INITIAL_FORM_QUERY_VALUE,
  INITIAL_EXECUTE_MODAL_FORM_QUERY_VALUE,
  LIST_NAME,
  LOAD_LIST_REQUEST_TASK_NAME,
  LOAD_EXECUTE_RECORD_LIST_REQUEST_TASK_NAME,
  EXECUTE_RECORD_LIST_NAME,
} from './constants';
import { loadAdjustPriceListApi, loadTaskExecuteRecordApi, canTaskApi } from './api';

export default class store extends ListStore {
  // Header 表单查询提交的数据
  formQueryValue = { ...INITIAL_FORM_QUERY_VALUE };

  // 点击表格行ID
  selectedRableRowId = '';

  executeModalValues = {
    visible: false,
    formQueryValue: { ...INITIAL_EXECUTE_MODAL_FORM_QUERY_VALUE },
  };

  constructor(config) {
    super(config);
  }

  setExecuteModalValues = params => {
    this.executeModalValues = {
      ...this.executeModalValues,
      ...params,
    };
  };

  // 重置
  onHeaderReset = value => {
    this.formQueryValue = value;
  };

  // 加载分时段调价记录列表
  loadAdjustPriceList = async ({ loadAction = 'reset', pageSize: inputPageSize, pageNum: inputPageNum } = {}) => {
    await this.loadList({
      requestTaskName: LOAD_LIST_REQUEST_TASK_NAME,
      listName: LIST_NAME,
      loadAction,
      pageSize: inputPageSize,
      pageNum: inputPageNum,
      loadDataFunc: async ({ pageSize, pageNum }) => {
        const { timeRange = [], ...restValue } = this.formQueryValue;
        const [startTime = null, endTime = null] = timeRange || [];
        const result = await loadAdjustPriceListApi({ ...restValue, timeRange: { startTime, endTime } }, { pageSize, pageNum });
        let { rows: data = [], total = 0 } = result || {};
        return { data, total };
      },
    });
  };

  // 获取调价记录列表
  loadExecuteRecordsList = async ({ loadAction = 'reset', pageSize: inputPageSize, pageNum: inputPageNum } = {}) => {
    await this.loadList({
      requestTaskName: LOAD_EXECUTE_RECORD_LIST_REQUEST_TASK_NAME,
      listName: EXECUTE_RECORD_LIST_NAME,
      loadAction,
      pageSize: inputPageSize,
      pageNum: inputPageNum,
      loadDataFunc: async ({ pageSize, pageNum }) => {
        const { timeRange = [] } = this.executeModalValues.formQueryValue;
        const [startTime = null, endTime = null] = timeRange || [];
        const result = await loadTaskExecuteRecordApi({
          masterTaskId: this.selectedRableRowId,
          timeRange: { startTime, endTime },
          page: { pageSize, pageNum },
        });
        let { rows: data = [], total = 0 } = result || {};
        return { data, total };
      },
    });
  };

  init = () => {
    this.loadAdjustPriceList({ loadAction: 'reset' });
  };

  // 点击查询
  onHeaderQuery = value => {
    this.formQueryValue = value;
    this.loadAdjustPriceList({ loadAction: 'reset' });
  };

  // 表格 pageSize 变更
  onTablePageSizeChange = ({ pageSize }) => {
    this.loadAdjustPriceList({ loadAction: 'pageSizeChange', pageSize });
  };

  // 表格 pageNum 变更
  onTablePageNumChange = ({ pageNum }) => {
    this.loadAdjustPriceList({ loadAction: 'pageNumChange', pageNum });
  };

  // 点击表格行任务记录
  onTableRowRecord = ({ id }) => {
    this.selectedRableRowId = id;
    this.setExecuteModalValues({ visible: true });
  };

  // 确认删除（调用删除接口）
  confirmCancelTask = async id => {
    try {
      await canTaskApi(id);
      this.loadAdjustPriceList({ loadAction: 'reset' });
    } catch (error) {
      errorHandler({ error });
    }
  };

  // 点击表格行取消任务点击
  onTableRowTaskCancel = ({ id } = {}) => {
    if (!id) {
      return;
    }
    MessageBox.confirm('此操作将取消该任务, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        this.confirmCancelTask(id);
      })
      .catch(() => {});
  };

  // ExecuteModal 关闭
  onExecuteModalClose = () => {
    this.selectedRableRowId = '';
    this.setExecuteModalValues({ visible: false });
    this.resetList(EXECUTE_RECORD_LIST_NAME);
  };

  // ExecuteModal 打开
  onExecuteModalOpen = () => {
    this.loadExecuteRecordsList({ loadAction: 'reset' });
  };

  // ExecuteModal 点击查询按钮
  onExecuteModalQuery = value => {
    this.setExecuteModalValues({ formQueryValue: value });
    this.loadExecuteRecordsList({ loadAction: 'reset' });
  };

  // ExecuteModal 点击重置按钮
  onExecuteModalReset = value => {
    this.setExecuteModalValues({ formQueryValue: value });
  };

  // ExecuteModal 表格分页数变更
  onExecuteModalPageSizeChange = ({ pageSize }) => {
    this.loadExecuteRecordsList({ loadAction: 'pageSizeChange', pageSize });
  };

  // ExecuteModal 表格当前页
  onExecuteModalPageNumChange = ({ pageNum }) => {
    this.loadExecuteRecordsList({ loadAction: 'pageNumChange', pageNum });
  };

  // ExecuteModal 表格行点击下载错误文件
  onExecuteModalDownErrorFile = async ({ id }) => {
    try {
      const result = await loadTaskLogsApi(id);
      if (!(result?.length > 0)) {
        throw new Error('没有可导出的数据');
      }
      const tHeader = ['渠道编码', '商品编码', '原因'];
      const filterVal = ['channelCode', 'goodsCode', 'reason'];
      const data = formatJson(filterVal, result);
      export_json_to_excel(tHeader, data, `商品调价错误日志(${dayjs(new Date()).format('MM月DD日')})-${id}`);
    } catch (error) {
      errorHandler({ error });
    }
  };
}
